package com.wgz.ssm.controller;

import com.wgz.ssm.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author wgz
 * Created by admin on 2021/3/30
 */
@Controller
public class UserController {
    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }

    //用户登录
    @PostMapping("/login")
    public String login(User user, Model model, HttpSession session){
        //获取用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();
        //此处模拟从数据库中获取用户名及密码进行判断
        if (username != null && username.equals("yuan") && password != null && password.equals("123456")){
            //将用户对象添加到session
            session.setAttribute("USER_SESSION",user);
            //重定向到主页面的跳转方法
            return "redirect:main";
        }
        model.addAttribute("msg","用户名或密码错误，请重新输入登录!");
        return "login";
    }
    //向用户主页面跳转
    @RequestMapping(value = "/main")
    public String toMain(){
        return "main";
    }

    //退出登录
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        //清楚Session
        session.invalidate();
        //重定向到登录页面的跳转方法
        return "redirect:login";
    }

}
